package com.hengxinguotong.zhihuichengjian.ui.device;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.bean.Device;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.BluetoothService;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.PrintPic;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;

import java.io.UnsupportedEncodingException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 二维码
 * Created by liux on 2017/3/1.
 */

public class QRCodeActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.qrcode_iv)
    ImageView qrcodeIv;
    @BindView(R.id.name_etv)
    HXTextView nameEtv;
    @BindView(R.id.number_etv)
    HXTextView numberEtv;
    @BindView(R.id.manufacturer_etv)
    HXTextView manufacturerEtv;
    @BindView(R.id.model_etv)
    HXTextView modelEtv;
    @BindView(R.id.personliable_etv)
    HXTextView personliableEtv;
    @BindView(R.id.print_tv)
    HXTextView printTv;
    @BindView(R.id.bluetooth_tv)
    HXTextView bluetoothTv;
    @BindView(R.id.bluetooth_rl)
    RelativeLayout bluetoothRl;
    private Device device;
    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    public static final String TOAST = "toast";
    public static final String DEVICE_NAME = "device_name";
    private String mConnectedDeviceName = null;
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    private BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the services
    public BluetoothService mService = null;
    // The Handler that gets information back from the BluetoothService

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case BluetoothService.STATE_CONNECTED:
                            bluetoothTv.setText("已连接:");
                            bluetoothTv.append(mConnectedDeviceName);
                            break;
                        case BluetoothService.STATE_CONNECTING:
                            bluetoothTv.setText("正在连接...");
                            break;
                        case BluetoothService.STATE_LISTEN:
                        case BluetoothService.STATE_NONE:
                            bluetoothTv.setText("无连接");
                            break;
                    }
                    break;
                case MESSAGE_WRITE:
                    //byte[] writeBuf = (byte[]) msg.obj;
                    // construct a string from the buffer
                    //String writeMessage = new String(writeBuf);
                    break;
                case MESSAGE_READ:
                    //byte[] readBuf = (byte[]) msg.obj;
                    // construct a string from the valid bytes in the buffer
                    //String readMessage = new String(readBuf, 0, msg.arg1);
                    break;
                case MESSAGE_DEVICE_NAME:
                    // save the connected device's name
                    mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                    showToast("连接至"
                            + mConnectedDeviceName);
                    break;
                case MESSAGE_TOAST:
                    Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qrcode);
        device = (Device) getIntent().getSerializableExtra("device");
        ButterKnife.bind(this);
        initView();
//        if (hasPrint()) {
        bluetoothRl.setVisibility(View.VISIBLE);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (!mBluetoothAdapter.isEnabled()) {
            bluetoothTv.setText("打开蓝牙");
        }else{
            bluetoothTv.setText("连接蓝牙设备");
        }

        if (mService == null) {
            mService = new BluetoothService(this, mHandler);
            mService.printCenter();
            mService.printSize(1);
        }


        if (mBluetoothAdapter == null) {
            showToast("您的设备不支持蓝牙");
            return;
        }

//        }
    }

    private void initView() {
        qrcodeIv.setImageBitmap(Utils.createQRcodeImage(Constants.DEVICE + device.getId()));
        nameEtv.setText(device.getName());
        numberEtv.setText(device.getNumber());
        manufacturerEtv.setText(device.getManufacturer());
        modelEtv.setText(device.getModel());
        personliableEtv.setText(device.getUserName());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CONNECT_DEVICE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    // Get the device MAC address
                    BluetoothDevice device = data.getParcelableExtra("bluetoothDevice");
                    // Get the BLuetoothDevice object
                    // Attempt to connect to the device
                    mService.connect(device);
                }
                break;
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    showToast("蓝牙已打开");
                    bluetoothTv.setText("连接蓝牙设备");
                } else {
                    bluetoothTv.setText("打开蓝牙");
                    showToast("蓝牙没有打开");
                }
        }
    }

    @OnClick({R.id.iv_back, R.id.print_tv, R.id.bluetooth_tv})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.print_tv:
                sendMessage(Utils.createQRcodeImage(Constants.DEVICE + device.getId()));
                sendMessage("\n\n\n");
                break;
            case R.id.bluetooth_tv:
                if(!mBluetoothAdapter.isEnabled()){
                    //打开蓝牙
                    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
                }else{
                    intent = new Intent(QRCodeActivity.this, BlueToothListActivity.class);
                    startActivityForResult(intent, REQUEST_CONNECT_DEVICE);
                }

                break;
        }
    }

    /**
     * 打印
     *
     * @param message
     */
    private void sendMessage(String message) {
        // Check that we're actually connected before trying anything
        if (mService.getState() != BluetoothService.STATE_CONNECTED) {
            Toast.makeText(this, "蓝牙没有连接", Toast.LENGTH_SHORT).show();
            return;
        }

        // Check that there's actually something to send
        if (message.length() > 0) {
            // Get the message bytes and tell the BluetoothService to write
            byte[] send;
            try {
                send = message.getBytes("GB2312");
            } catch (UnsupportedEncodingException e) {
                send = message.getBytes();
            }

            mService.write(send);
        }
    }


    private void sendMessage(Bitmap bitmap) {
        // Check that we're actually connected before trying anything
        if (mService.getState() != BluetoothService.STATE_CONNECTED) {
            Toast.makeText(this, "蓝牙没有连接", Toast.LENGTH_SHORT).show();
            return;
        }
        // 发送打印图片前导指令
        byte[] start = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B,
                0x40, 0x1B, 0x33, 0x00};
        mService.write(start);

        /**获取打印图片的数据**/
//		byte[] send = getReadBitMapBytes(bitmap);

        mService.printCenter();
        PrintPic.getInstance().init(bitmap);
        mService.write(PrintPic.getInstance().printDraw());
        // 发送结束指令
        byte[] end = {0x1d, 0x4c, 0x1f, 0x00};
        mService.write(end);
    }


}
